package com.smartstate.dataManagement.config;

import com.smartstate.dataManagement.core.ScheduleConstants;
import com.smartstate.dataManagement.entity.Equipment;
import com.smartstate.dataManagement.entity.EquipmentConfiguration;
import com.smartstate.dataManagement.entity.QuartzJob;
import com.smartstate.dataManagement.mapper.EquipmentConfigMapper;
import com.smartstate.dataManagement.mapper.EquipmentMapper;
import com.smartstate.dataManagement.mapper.QuartzMapper;
import com.smartstate.dataManagement.service.IQuartzJobService;
import com.smartstate.dataManagement.util.QuartzUtils;
import lombok.extern.log4j.Log4j2;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Component
@Log4j2
public class MyApplicationRunner implements ApplicationRunner {

    @Resource
    private QuartzMapper quartzMapper;

    @Resource
    private EquipmentMapper equipmentMapper;

    @Resource
    private EquipmentConfigMapper equipmentConfigMapper;

    @Resource
    private IQuartzJobService iQuartzJobService;

//
//    @Resource
//    private IQuartzJobService quartzService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.err.println("------------------------" + "项目启动时间：" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")) + "-----------------------");

        int count = 0;

        //项目启动的时候，把定时任务表quartz_job里的数据清空，在往里面添加定时任务
//        quartzMapper.deleteAll();
        List<QuartzJob> quartzJobs = quartzMapper.findAll();
        for (QuartzJob quartzJob : quartzJobs) {
            iQuartzJobService.deleteJob(quartzJob);
        }

        //获取所有的设备
        List<Equipment> equipmentList = equipmentMapper.findAll();
        if (!CollectionUtils.isEmpty(equipmentList)) {
            //遍历这些设备
            for (Equipment equipment : equipmentList) {
                //根据设备id查询设备属性表，判断tags是否有值,有值才创建定时任务
                EquipmentConfiguration configuration = equipmentConfigMapper.selectOne(equipment.getDeviceId());
                if ((configuration != null) && (configuration.getTags() != null)) {
                    QuartzJob quartzJob = new QuartzJob();
                    Integer type = equipment.getType();  //设备类型
                    String cycle = equipment.getCycle(); //采集周期
                    String deviceId = equipment.getDeviceId(); //设备id
                    //根据设备类型来设置定时任务调用的方法
                    String invokeTarget = QuartzUtils.type(equipment.getId(), type);
                    //根据采集周期设置定时任务的采集周期
                    String corn = QuartzUtils.cycle(cycle);
                    quartzJob.setJobName(deviceId);
                    quartzJob.setJobGroup("DEFAULT");
                    quartzJob.setInvokeTarget(invokeTarget);
                    quartzJob.setCronExpression(corn);
                    quartzJob.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
                    quartzJob.setConcurrent("1");
                    quartzJob.setStatus("0");
                    quartzJob.setRemark(deviceId + "的定时任务");
                    int insert = iQuartzJobService.insertJob(quartzJob);
                    if (insert > 0) {
                        count++;
                    }
                }
            }
        }
        System.err.println("一共执行了： " + count + "次");


        //每过十分钟，判断一下设备有没有修改
        QuartzJob job = new QuartzJob();
        job.setJobName("默认定时任务");
        job.setJobGroup("DEFAULT");
        job.setInvokeTarget("quartz.updateQuartz('')");
        job.setCronExpression("0 0/10 * * * ?");
        job.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);
        job.setConcurrent("1");
        job.setStatus("0");
        job.setRemark("每过十分钟，判断一下设备有没有修改");
        int insert = iQuartzJobService.insertJob(job);


        //如果设备的采集方式是plc采集，就添加定时任务，去Redis中查询设备的报警上下限
        boxCollect();

    }



    private void boxCollect() {
        //如果设备的采集方式是plc采集，就添加定时任务，去Redis中查询设备的报警上下限
        //查询是plc采集方式的所有设备
        List<String> deviceIds = equipmentConfigMapper.findAllIsWay("plc");
        //根据deviceId集合去设备表查找到设备对应的主键id
        deviceIds.stream().forEach(deviceId -> {
            Equipment one = equipmentMapper.getOne(deviceId);
            QuartzJob quartzJob = null;
            if (one != null) {
                quartzJob = new QuartzJob();
                quartzJob.setJobName(one.getDeviceId());//定时器的名称
                quartzJob.setJobGroup("ACQUISITIONMETHODS");//定时器的分组
                quartzJob.setInvokeTarget("quartz.PLCCollect('" + one.getId() + "')");//定时器执行的方法
                quartzJob.setCronExpression("0/10 * * * * ?");//采集周期
                quartzJob.setMisfirePolicy(ScheduleConstants.MISFIRE_IGNORE_MISFIRES);//立即执行
                quartzJob.setConcurrent("1");//是否允许并发执行
                quartzJob.setStatus("0");//状态
                quartzJob.setRemark("定时读取" + one.getDeviceId() + "设备的属性上下限");//备注
                try {
                    iQuartzJobService.insertJob(quartzJob);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        });
    }

}
